<?php

namespace app\admin\controller;

use app\admin\model\vppz\User;
use app\common\controller\Backend;
use Exception;
use PDOException;
use think\Db;
use think\exception\ValidateException;

/**
 * 通知消息管理
 *
 * @icon fa fa-circle-o
 */
class Message extends Backend
{

    /**
     * MessageNotice模型对象
     * @var \addons\message\model\MessageNotice
     */
    protected $model = null;
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \addons\message\model\MessageNotice;
        $this->messageUserModel = new \addons\message\model\MessageUser;
        $this->userModel = new \app\admin\model\vppz\User;
        $this->familyModel = new \app\admin\model\vppz\FamilyMembers;
        $this->view->assign("messageTypeList", $this->model->getMessageTypeList());
        $this->view->assign("TypeList", $this->model->getTypeList());
        $this->view->assign("messageMbTypeList", $this->model->getMessageMbTypeList());
    }


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->visible(['message_id','status', 'message_type', 'message_title', 'message_content', 'createtime', 'updatetime']);
            }
            $list = collection($list)->toArray();
            if (empty($list) === FALSE){
                foreach ($list as &$v){
                    $v['message_to'] = '平台';
                    if($v['message_type'] == 'user'){
                        $user_id = $this->messageUserModel->where([
                            'message_id'=>$v['message_id']
                        ])->value('user_id');
                        $v['message_to'] = '未知';
                        if(empty($user_id) === FALSE){
                            $v['message_to'] = $this->userModel->where([
                                'id'=>$user_id
                            ])->value('nickname');
                        }
                    }
                }
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $user_id = isset($params['user_id']) ? $params['user_id'] : 0;
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);

                    //个体消息：此处直接发送，如果是群体消息则需要自行实现用户前台触发
                    if ($params['message_type'] == 'user') {
                        $messageUser = new \addons\message\model\MessageUser;
                        $messageUser->save(['user_id' => $user_id, 'message_id' => $this->model->message_id]);
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if ($row['message_type'] == 'user') {
            $row['user_id'] = Db::name('message_user')->where(['message_id' => $row['message_id']])->value('user_id');
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 发送模板消息
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
 public function sendmb()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $user_id = isset($params['user_id']) ? $params['user_id'] : 0;
                $params = $this->preExcludeFields($params);
                $result = false;
                //测试一条
                $openid = 'ozgtZ7JIkSNfheGrDwI9JsDH99rI';
                if ($params['typeid'] == 'yimiao'){
                    $res = \TempNotice::yimiaojiezhong($openid,'测试账号',$params['message_address'],$params['message_yimiao_content']);
                }elseif ($params['typeid'] == 'wenzhen'){
                    $res = \TempNotice::wenzhentixing($params['message_title'],$params['message_content'],$openid);
                }else{
                    $senddata = array(
                        'openid'=>$openid,
                        'name'=>$params['username'],
                        'keshi'=>$params['keshi'],
                        'hospital'=>$params['hospital'],
                        'date'=>$params['date'],
                        'content'=>$params['content'],
                    );
                    $res = \TempNotice::jiuzhentixing($senddata);
                }
            }
                if($res['errcode'] == 0){
                    try {
                        if ($params['typeid'] == 'yimiao'){
                            if($params['message_type'] == 'user'){
                                $data = array(
                                    'user_id'=>$user_id,
                                    'send_type'=>'user',
                                    'content'=>json_encode(array(
                                        'address'=>$params['message_address'],
                                        'content'=>$params['message_yimiao_content'],
                                    )),
                                    'type'=>'yimiao'
                                );
                            }else{
                                $data = array(
                                    'user_id'=>$user_id,
                                    'send_type'=>'all',
                                    'content'=>json_encode(array(
                                        'address'=>$params['message_address'],
                                        'content'=>$params['message_yimiao_content'],
                                    )),
                                    'type'=>'yimiao'
                                );
                            }
                        }elseif ($params['typeid'] == 'wenzhen'){
                            if($params['message_type'] == 'user'){
                                $data = array(
                                    'user_id'=>$user_id,
                                    'send_type'=>'user',
                                    'content'=>json_encode(array(
                                        'address'=>$params['message_address'],
                                        'content'=>$params['message_yimiao_content'],
                                    )),
                                    'type'=>'wenzhen'
                                );
                            }else{
                                $data = array(
                                    'user_id'=>$user_id,
                                    'send_type'=>'all',
                                    'content'=>json_encode(array(
                                        'address'=>$params['message_title'],
                                        'content'=>$params['message_content'],
                                    )),
                                    'type'=>'wenzhen'
                                );
                            }
                        }elseif ($params['typeid'] == 'jiuzhen'){
                            if($params['message_type'] == 'user'){
                                $data = array(
                                    'user_id'=>$user_id,
                                    'send_type'=>'user',
                                    'content'=>json_encode(array(
                                        'username'=>$params['username'],
                                        'hospital'=>$params['hospital'],
                                        'keshi'=>$params['keshi'],
                                        'date'=>$params['date'],
                                        'content'=>$params['content'],
                                    )),
                                    'type'=>'jiuzhen'
                                );
                            }else{
                                $data = array(
                                    'user_id'=>$user_id,
                                    'send_type'=>'all',
                                    'content'=>json_encode(array(
                                        'username'=>$params['username'],
                                        'hospital'=>$params['hospital'],
                                        'keshi'=>$params['keshi'],
                                        'date'=>$params['date'],
                                        'content'=>$params['message_content'],
                                    )),
                                    'type'=>'jiuzhen'
                                );
                            }
                        }
                        $queue = new \app\admin\model\vppz\MsQueue();
                        $result = $queue->save($data);
                    } catch (ValidateException $e) {
                        $this->error($e->getMessage());
                    } catch (PDOException $e) {
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        $this->error($e->getMessage());
                    }

                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error(__('No rows were inserted'));
                    }
                }else{
                    if ($params['typeid'] == 'yimiao'){
                        if (strpos($res['errmsg'], 'thing4.value') !== false) {
                            $this->error('接种地点格式有误，请重新编辑');
                        }elseif (strpos($res['errmsg'], 'thing7.value') !== false) {
                            $this->error('提示说明格式有误，请重新编辑');
                        }else{
                            $this->error('当前用户未订阅消息');
                        }
                    }elseif ($params['typeid'] == 'wenzhen'){
                        if (strpos($res['errmsg'], 'thing2.value') !== false) {
                            $this->error('提醒内容格式有误，请重新编辑');
                        }elseif (strpos($res['errmsg'], 'thing4.value') !== false) {
                            $this->error('提示说明格式有误，请重新编辑');
                        }else{
                            $this->error('当前用户未订阅消息');
                        }
                    }elseif ($params['typeid'] == 'jiuzhen'){
                        if (strpos($res['errmsg'], 'name1.value') !== false) {
                            $this->error('就诊人格式有误，请重新编辑');
                        }elseif (strpos($res['errmsg'], 'thing4.value') !== false) {
                            $this->error('就诊科室格式有误，请重新编辑');
                        }elseif (strpos($res['errmsg'], 'thing8.value') !== false) {
                            $this->error('就诊医院格式有误，请重新编辑');
                        }elseif (strpos($res['errmsg'], 'date5.value') !== false) {
                            $this->error('就诊时间格式有误，请重新编辑');
                        }elseif (strpos($res['errmsg'], 'thing7.value') !== false) {
                            $this->error('提示说明格式有误，请重新编辑');
                        }else{
                            $this->error('当前用户未订阅消息');
                        }
                    }
                }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

 public function sendmsg($ids = null)
    {
        if (!$ids){
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $userids = $this->familyModel->whereIn('id',$ids)->column('user_id');
            $params = $this->request->post("row/a");

            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                //测试一条
                $openid = 'ozgtZ7JIkSNfheGrDwI9JsDH99rI';
                if ($params['typeid'] == 'yimiao'){
                    $res = \TempNotice::yimiaojiezhong($openid,'测试账号',$params['message_address'],$params['message_yimiao_content']);
                }elseif ($params['typeid'] == 'wenzhen'){
                    $res = \TempNotice::wenzhentixing($params['message_title'],$params['message_content'],$openid);
                }else{
                    $senddata = array(
                        'openid'=>$openid,
                        'name'=>$params['username'],
                        'keshi'=>$params['keshi'],
                        'hospital'=>$params['hospital'],
                        'date'=>$params['date'],
                        'content'=>$params['content'],
                    );
                    $res = \TempNotice::jiuzhentixing($senddata);
                }
            }
                if($res['errcode'] == 0){
                    try {
                        if ($params['typeid'] == 'yimiao'){
                            $data = array(
                                'user_id'=>$userids,
                                'send_type'=>'select',
                                'content'=>json_encode(array(
                                    'address'=>$params['message_address'],
                                    'content'=>$params['message_yimiao_content'],
                                )),
                                'type'=>'yimiao'
                            );
                        }elseif ($params['typeid'] == 'wenzhen'){
                                $data = array(
                                    'user_id'=>$userids,
                                    'send_type'=>'select',
                                    'content'=>json_encode(array(
                                        'address'=>$params['message_title'],
                                        'content'=>$params['message_content'],
                                    )),
                                    'type'=>'wenzhen'
                                );
                        }elseif ($params['typeid'] == 'jiuzhen'){
                            $data = array(
                                    'user_id'=>$userids,
                                    'send_type'=>'select',
                                    'content'=>json_encode(array(
                                        'username'=>$params['username'],
                                        'hospital'=>$params['hospital'],
                                        'keshi'=>$params['keshi'],
                                        'date'=>$params['date'],
                                        'content'=>$params['message_content'],
                                    )),
                                    'type'=>'jiuzhen'
                                );
                        }

                        $queue = new \app\admin\model\vppz\MsQueue();
                        $result = $queue->save($data);
                    } catch (ValidateException $e) {
                        $this->error($e->getMessage());
                    } catch (PDOException $e) {
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        $this->error($e->getMessage());
                    }
                    if ($result) {
                        $this->success('消息发送成功', '/admin888.php/vppz/family_members?ref=addtabs', []);
                    } else {
                        $this->error(__('No rows were inserted'));
                    }
                }else{
                    if ($params['typeid'] == 'yimiao'){
                        if (strpos($res['errmsg'], 'thing4.value') !== false) {
                            $this->error('接种地点格式有误，请重新编辑');
                        }elseif (strpos($res['errmsg'], 'thing7.value') !== false) {
                            $this->error('提示说明格式有误，请重新编辑');
                        }else{
                            $this->error('当前用户未订阅消息');
                        }
                    }elseif ($params['typeid'] == 'wenzhen'){
                        if (strpos($res['errmsg'], 'thing2.value') !== false) {
                            $this->error('提醒内容格式有误，请重新编辑');
                        }elseif (strpos($res['errmsg'], 'thing4.value') !== false) {
                            $this->error('提示说明格式有误，请重新编辑');
                        }else{
                            $this->error('当前用户未订阅消息');
                        }
                    }elseif ($params['typeid'] == 'jiuzhen'){
                        if (strpos($res['errmsg'], 'name1.value') !== false) {
                            $this->error('就诊人格式有误，请重新编辑');
                        }elseif (strpos($res['errmsg'], 'thing4.value') !== false) {
                            $this->error('就诊科室格式有误，请重新编辑');
                        }elseif (strpos($res['errmsg'], 'thing8.value') !== false) {
                            $this->error('就诊医院格式有误，请重新编辑');
                        }elseif (strpos($res['errmsg'], 'date5.value') !== false) {
                            $this->error('就诊时间格式有误，请重新编辑');
                        }elseif (strpos($res['errmsg'], 'thing7.value') !== false) {
                            $this->error('提示说明格式有误，请重新编辑');
                        }else{
                            $this->error('当前用户未订阅消息');
                        }
                    }
                }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                $msg_ids = [];
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                    $msg_ids[] = $v[$pk];
                }
                Db::name('message_user')->where(['message_id' => ['in', implode(',', $msg_ids)]])->delete();
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    public function readall()
    {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where('status', '=', 0)->select();

            try {
                if(empty($list) === FALSE){
                    $this->model->where('status', '=', 0)->update(array(
                        'status'=>1,
                        'updatetime'=>time()
                    ));
                }
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
           $this->success();
    }
}
